package server.mapper;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @Author: zhouchao
 * @Date: 2021/06/21 10:12
 * @Description:
 */
public class CustomClassloader extends ClassLoader {

    private String name;
    private String path;

    public CustomClassloader(String name, String path) {
        this.name = name;
        this.path = path;
    }

    @Override
    public Class<?> findClass(String name) {
        File file = new File(this.path);
        Class<?> c = null;
        try {
            byte[] bytes = getClassBytes(file);
            //defineClass方法可以把二进制流字节组成的文件转换为一个java.lang.Class
            c = this.defineClass(name, bytes, 0, bytes.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return c;
    }

    private byte[] getClassBytes(File file) {
        if (file.exists()) {
            FileInputStream in = null;
            ByteArrayOutputStream out = null;
            try {
                in = new FileInputStream(file);
                out = new ByteArrayOutputStream();

                byte[] buffer = new byte[1024];
                int size = 0;
                while ((size = in.read(buffer)) != -1) {
                    out.write(buffer, 0, size);
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    in.close();
                } catch (IOException e) {

                    e.printStackTrace();
                }
            }
            return out.toByteArray();
        } else {
            return null;
        }
    }

    @Override
    public String toString() {
        return this.name;
    }
}
